package com.soft.small.app.mqtt;

import com.alibaba.fastjson.JSONObject;
import com.soft.small.util.MqttMessageUtil;
import com.soft.small.util.mqtt.MyMqttClient;
import com.uiotsoft.entity.MessageConvert;
import com.uiotsoft.entity.MessageWrapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

@Data
@Slf4j
public class AppMqttCallback implements MqttCallback {
    private MyMqttClient mqttClient;
    private String appSecret;

    public AppMqttCallback(MyMqttClient mqttClient){
        this.mqttClient = mqttClient;
    }

    @Override
    public void connectionLost(Throwable throwable) {
        log.info("app连接丢失……");
    }

    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) {
        MessageWrapper messageWrapper = MqttMessageUtil.getMessageData(mqttMessage.getPayload());

        MessageConvert messageConvert = MqttMessageUtil.decry(messageWrapper, mqttClient.getAppSecret());
        JSONObject result = messageConvert.getMessage();

        log.info("app收到的消息ID为：{}\n ++++++主题为：{}\n ++++++数据为：{}",mqttMessage.getId(),s,result);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }
}
